//
//  GoodsCommentViewController.m
//  Housekeeping
//
//  Created by 刘建峰 on 16/6/2.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "GoodsCommentViewController.h"
#import "GoodsComentTableViewCell.h"
static NSString *cellIdentify = @"GoodsComentTableViewCell";
@interface GoodsCommentViewController ()<UITableViewDataSource,UITableViewDelegate>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;
@property (weak, nonatomic) IBOutlet UIView *navView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property(nonatomic,strong)NSMutableArray * commitArray;
@property(nonatomic,strong)NSMutableArray * heightArray;

@end

@implementation GoodsCommentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _pageNO = 1;
    // Do any additional setup after loading the view.
    _heightArray = [NSMutableArray array];
    _commitArray = [NSMutableArray array];
    [self initViewLayout];
    [self addRefreshing];
}

- (void)initViewLayout{
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    //注册
    [self.tableView registerNib:[UINib nibWithNibName:cellIdentify bundle:nil] forCellReuseIdentifier:cellIdentify];
    
}

- (IBAction)back:(id)sender {
    [self backBtn];
}

#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.tableView.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getCommentsList];
        });
    }];
    // 马上进入刷新状态
    [self.tableView.header beginRefreshing];
}
//加载更多数据
- (void)loadMoreData{
    if (self.commitArray.count == _totle) {
        [self.tableView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getCommentsList];
        });
    }
    
}


#pragma mark === 获取评论列表
- (void)getCommentsList{
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:[NSNumber numberWithInt:_pageNO] forKey:@"page"];
    [dic setObject:[NSNumber numberWithInt:PageSize] forKey:@"pageSize"];
    [dic setObject:_goodsId forKey:@"goodsId"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:HK_queryAppMallGoodsComment withHttpType:@"POST" withTag:HK_HK_queryAppMallGoodsComment];
}


#pragma mark -- UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _commitArray.count;
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height= [_heightArray[indexPath.row] floatValue]*VerticalRatio();
    return height ;
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    GoodsComentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify];
    if (cell == nil) {
        cell= [[GoodsComentTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentify];
        
    }
    for (UIView *view in cell.subviews) {
        if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
            [view removeFromSuperview];
        }
    }
    cell.headImage.frame = flexibleFrame(CGRectMake(10, 11, 26, 26), NO);
    cell.headImage.layer.cornerRadius = 13*VerticalRatio();
    NSDictionary * dic = _commitArray[indexPath.row];
    NSString * image = dic[@"memeberIcon"];
    if (image) {
        [cell.headImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,image]]];
    }else{
        cell.headImage.image = [UIImage imageNamed:@"comment1"];
    }
    
    
    cell.commentInfo.frame = flexibleFrame(CGRectMake(47, 40, 265, 15), YES);
    cell.commentInfo.numberOfLines = 0;
    cell.commentInfo.text = [NSString stringWithFormat:@"%@",dic[@"mgcoContent"]];
    [cell.commentInfo sizeToFit];
    
    cell.name.frame = flexibleFrame(CGRectMake(47, 17, 118, 15), NO);
    cell.name.text = [NSString stringWithFormat:@"%@",dic[@"memberName"]];
    
    cell.date.frame = flexibleFrame(CGRectMake(168, 16, 144, 15), NO);
    NSString * date = [NSString stringWithFormat:@"%@",dic[@"mgcoDate"]];
    if (date && date.length>=19) {
        cell.date.text = [date substringToIndex:19];
    }
    
    
    NSString * images = [NSString stringWithFormat:@"%@",dic[@"mgcoImage"]];
    NSArray * imagesArray = [images componentsSeparatedByString:@","];
    
    CGFloat height= [_heightArray[indexPath.row] floatValue];
    for (int i = 0; i<imagesArray.count; i++) {
        UIImageView * image = [[UIImageView alloc]initWithFrame:flexibleFrame(CGRectMake(50+i*58, height-60, 50, 50), NO)];
        [image sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,imagesArray[i]]]];
        [cell addSubview:image];
    }
    
    cell.line.frame = flexibleFrame(CGRectMake(0, height-1, 320, 1), NO);
    
    return cell;
    
}


#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    [_tableView.header endRefreshing];
    [_tableView.footer endRefreshing];
    if (tag==HK_HK_queryAppMallGoodsComment) {
        
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            dispatch_async(dispatch_get_main_queue(), ^{
                _totle = [database[@"result"][@"total"] integerValue];
                if (_totle > PageSize) {
                    __weak __typeof(self) weakSelf = self;
                    if (!self.tableView.footer) {
                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                        self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                            [weakSelf loadMoreData];
                        }];
                    }
                }
                if (self.pageNO == 1) {
                    [self.commitArray removeAllObjects];
                }
                NSArray *arr = database[@"result"][@"rows"];
                for (id entity in arr) {
                    [self.commitArray addObject:entity];
                }
               
                
                for (int i = 0; i<_commitArray.count; i++) {
                    NSString * commentImage = _commitArray[i][@"mgcoImage"];
                    NSString * comment = _commitArray[i][@"mgcoContent"];
                    NSInteger height = 0;
                    if (commentImage.length==0 ) {
                        height = 68;
                    }else{
                        height = 118;
                    }
                    
                    
                    int lines = 0;
                    CGSize cSize = [comment sizeWithFont:[UIFont systemFontOfSize:14*VerticalTexeRatio()]];
                    lines = cSize.width/(265*VerticalRatio()) + 1 ;
                    
                    height  += lines * 17;
                    
                    [_heightArray addObject:@(height)];
                }
                
            
                _tableView.delegate = self;
                _tableView.dataSource = self;
                [_tableView reloadData];
                

            });
            
        }
    }
}

-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
     [self dismissWaitDialog];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
